import { http } from "@/utils"
import { LocationQuery, useRoute, useRouter } from 'vue-router'
import { RouteLocationNormalizedLoaded, Router } from "vue-router"

type PagingOption = {
  pageIndex?: number
  pageSize?: number
  replace?: boolean
  where?: {[k: string]: any}
}

/** 分页助手 */
export class PagingHelper {

  private url: string
  private router: Router
  private query: LocationQuery

  constructor(_url: string, route: RouteLocationNormalizedLoaded, router: Router){
    this.url = _url
    this.router = router
    this.query = JSON.parse(JSON.stringify(route.query || {}))
  }
  
  /** 每页数据数 */
  public get pageSize () {
    return Number(this.query.pageSize) || null
  }

  /** 当前页 */
  public get pageIndex () {
    return Number(this.query.pageIndex || 1)
  }

  /** 设置url地址 */
  public setUrl(_url: string){
    this.url = _url
  }

  /** 执行分页 */
  public async paging<T = any>(opt: PagingOption ): Promise<{ total: number, data: Array<T>, lastData?: T }> {
    const where = this.compilePagingWhere(opt)
    if(opt.replace) this.replaceRouterQuery(where)
    const res = await http.get(this.url, where)
    if(opt.replace) this.replaceRouterQuery(where)
    return res
  }
  
  /** 编译分页条件 */
  public compilePagingWhere(opt: PagingOption): { [k: string]: any }{
    const where: any = {}
    if(opt.where) {
      for(const k in opt.where || {}){
        const val = opt.where[k]
        if(val) {
          const key = k.replace('page', '')
          where[key] = val
        }
      }
      for(const k in this.query){
        const val = opt.where[k]
        if(val && k.indexOf('page') != -1) {
          const key = k.replace('page', '')
          where[key] = val
        }
      }
    }
    where.pageSize = opt.pageSize || Number(this.query.pageSize)
    where.pageIndex = opt.pageIndex || Number(this.query.pageIndex || 1) 
    return where
  }
  
  private replaceRouterQuery(wh: { [k: string]: any }){
    const where: any = {}
    if(wh) {
      for(const k in wh){
        const val = wh[k]
        if(val) {
          const key = k.indexOf('page') == -1 ? `page${k}` : k
          where[key] = val
        }
      }
    }
    for(const k in this.query){
      const jud = Object.keys(where).indexOf(k) == -1
      if(jud) where[k] = this.query[k]
    }
    this.router.replace({ query: where }) 
  }
  
}

/** 分页查询 */
export const usePaging = (url: string) => {
  const route = useRoute()
  const router = useRouter()
  return new PagingHelper(url, route, router)
}

